#pragma once

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


#include "Log.hpp"


#define BACKLOG 10      //listen 全连接队列长度

class TcpServer
{
private:
    int16_t _port;
    int _listenSock = -1;
    static TcpServer* tcpServer;

private:
    TcpServer(int16_t port)
        :_port(port)
    {}
    TcpServer(const TcpServer& other) = delete;
    const TcpServer& operator=(const TcpServer& other) = delete;

public:
    //设置为单例
    static TcpServer* GetInstance(int16_t port)
    {
        static pthread_mutex_t svrMtx = PTHREAD_MUTEX_INITIALIZER;
        if(tcpServer == nullptr)
        {
            pthread_mutex_lock(&svrMtx);
            if(tcpServer == nullptr)
            {
                tcpServer = new TcpServer(port);
                tcpServer->Init();
            }
            pthread_mutex_unlock(&svrMtx);
        }
        return tcpServer;
    }

    void Init()
    {
        Socket();
        Bind();
        Listen();
        LOG(NORMAL, "tcpServer init success");
    }

    void Socket()
    {
        _listenSock = socket(AF_INET, SOCK_STREAM, 0);
        if(_listenSock < 0)
        {
            LOG(FATAL, "build sock fail");
            exit(1);
        }
        //地址|端口 复用，让服务器挂掉能马上又跑起来
        int opt = 1;
        setsockopt(_listenSock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }

    void Bind()
    {
        struct sockaddr_in local;
        //bzero(&local, sizeof(local));
        memset(&local, 0, sizeof(local));

        local.sin_family = AF_INET;
        local.sin_port = htons(_port);      //绑定端口
        
        local.sin_addr.s_addr = INADDR_ANY; //不绑定机器//云服务器不能直接绑定公网ip


        if(bind(_listenSock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind fail");
            exit(2);                        //绑定失败
        }

    }

    void Listen()
    {
        if(listen(_listenSock, BACKLOG) < 0)
        {
            LOG(FATAL, "listen fail");
            exit(3);            //
        }
        LOG(NORMAL, "listening...");
    }


    int Sockfd()
    {
        return _listenSock;
    }

    ~TcpServer()
    {
        if(_listenSock >= 0)
            close(_listenSock);
    }

};

TcpServer* TcpServer::tcpServer = nullptr;
